<template>
  <div class="user-wrapper" :class="theme">
    <span class="action" @click="showClick">
      <a-icon type="search"></a-icon>
    </span>
    <component
      :is="searchMenuComp"
      v-show="searchMenuVisible || isMobile()"
      class="borders"
      :visible="searchMenuVisible"
      title="搜索菜单"
      :footer="null"
      @cancel="searchMenuVisible=false">
      <a-select
        class="search-input"
        showSearch
        :showArrow="false"
        placeholder="搜索菜单"
        optionFilterProp="children"
        :filterOption="filterOption"
        :open="isMobile()?true:null"
        :getPopupContainer="(node) => node.parentNode"
        :style="isMobile()?{width: '100%',marginBottom:'50px'}:{}"
        @change="searchMethods"
        @blur="hiddenClick"
      >
        <a-select-option v-for="(site,index) in searchMenuOptions" :key="index" :value="site.id">{{ site.meta.title }}</a-select-option>
      </a-select>
    </component>
    <!-- <span class="action">
      <a class="logout_title" target="_blank" href="">
        <a-icon type="question-circle-o"></a-icon>
      </a>
    </span> -->
    <a-dropdown>
      <span class="action action-full ant-dropdown-link user-dropdown-menu">
        <a-avatar class="avatar" size="small" :src="getAvatar()"/>
        <span v-if="isDesktop()">欢迎您，{{ nickname() }}</span>
      </span>
      <a-menu slot="overlay" class="user-dropdown-menu-wrapper">
        <a-menu-item key="1">
          <router-link :to="{ name: 'account-settings-base' }">
            <a-icon type="setting"/>
            <span>个人中心</span>
          </router-link>
        </a-menu-item>
        <a-menu-item key="3" @click="systemSetting">
          <a-icon type="tool"/>
          <span>系统设置</span>
        </a-menu-item>
        <a-menu-item key="4" @click="updatePassword">
          <a-icon type="setting"/>
          <span>密码修改</span>
        </a-menu-item>
        <a-menu-item v-if="isMultiTenant" key="5" @click="updateCurrentTenant">
          <a-icon type="cluster"/>
          <span>切换租户</span>
        </a-menu-item>
        <a-menu-item key="6" @click="clearCache">
          <a-icon type="sync"/>
          <span>清理缓存</span>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <span class="action" @click="handleLogout">
      <a class="logout_title" href="javascript:;">
        <a-icon type="logout"/>
        <span v-if="isDesktop()">&nbsp;退出登录</span>
      </a>
    </span>
    <user-password ref="userPassword"></user-password>
    <tenant-select ref="tenantSelect" :closable="true" title="组织切换"></tenant-select>
    <setting-drawer ref="settingDrawer" :closable="true" title="系统设置"></setting-drawer>
  </div>
</template>

<script>
  import HeaderNotice from '../notice/HeaderNotice.vue'
  import UserPassword from './UserPassword.vue'
  import SettingDrawer from '@/components/setting/SettingDrawer';
  import TenantSelect from './TenantSelect.vue'
  import { mapActions, mapGetters, mapState } from 'vuex'
  import { mixinDevice } from '@/utils/mixin.js'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import Vue from 'vue'
  import { UI_CACHE_DB_DICT_DATA, IS_MULTI_TENANT } from '@/store/mutation-types'
  import { refreshDictCache, queryDictItems } from '@/views/sysConfig/dict/service.js'
  import { routerUri } from '@/api/common.js'

  export default {
    name: 'UserMenu',
    mixins: [mixinDevice],
    data() {
      return {
        searchMenuOptions: [],
        searchMenuComp: 'span',
        searchMenuVisible: false,
        isMultiTenant: Vue.ls.get(IS_MULTI_TENANT)
      }
    },
    components: {
      HeaderNotice,
      UserPassword,
      TenantSelect,
      SettingDrawer
    },
    props: {
      theme: {
        type: String,
        required: false,
        default: 'dark'
      }
    },
    created() {
      let lists = []
      this.searchMenus(lists, this.permissionMenuList)
      this.searchMenuOptions = [...lists]
    },
    computed: {
      ...mapState({
        // 后台菜单
        permissionMenuList: state => state.user.permissionList

      })
    },
    watch: {
      device: {
        immediate: true,
        handler() {
          this.searchMenuVisible = false
          this.searchMenuComp = this.isMobile() ? 'a-modal' : 'span'
        }
      },
      isMultiTenant: {
        immediate: true,
        handler(value) {
          this.isMultiTenant = value;
          if (String(process.env.VUE_APP_SSO) =='true' && String(this.isMultiTenant) =='true') {
            setTimeout(() => {
              this.updateCurrentTenant();
            }, 1500)
          }
        }
      }
    },
    methods: {
      showClick() {
        this.searchMenuVisible = true
      },
      hiddenClick() {
        this.shows = false
      },
      ...mapActions(['Logout']),
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      getAvatar() {
        return getFileAccessHttpUrl(this.avatar())
      },
      handleLogout() {
        const that = this

        this.$confirm({
          title: '提示',
          content: '真的要注销登录吗 ?',
          onOk() {
            return that.Logout({}).then(() => {
              that.$router.push({ path: routerUri.login });
            }).catch(err => {
              that.$message.error({
                title: '错误',
                description: err.message
              })
            })
          },
          onCancel() {
          }
        });
      },
      updatePassword() {
        let username = this.userInfo().username
        this.$refs.userPassword.show(username)
      },
      updateCurrentTenant() {
        this.$refs.tenantSelect.show()
      },
      systemSetting() {
        this.$refs.settingDrawer.showDrawer()
      },
      searchMenus(arr, menus) {
        for (let i of menus) {
          if (!i.hidden && i.component !== 'layouts/RouteView') {
           arr.push(i)
          }
          if (i.children && i.children.length > 0) {
            this.searchMenus(arr, i.children)
          }
        }
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      searchMethods(value) {
        let route = this.searchMenuOptions.filter(item => item.id === value)[0]
        if (route.meta.internalOrExternal === true || route.component.includes('layouts/IframePageView')) {
          window.open(route.meta.url, '_blank')
        } else {
          this.$router.push({ path: route.path })
        }
        this.searchMenuVisible = false
      },
      clearCache() {
        refreshDictCache().then((res) => {
          if (res.success) {
            queryDictItems().then((res) => {
              if (res.success) {
                Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
                Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
              }
            })
            this.$message.success('刷新缓存完成！');
          }
        }).catch(e => {
          this.$message.warn('刷新缓存失败！');
          console.log('刷新失败', e)
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-wrapper .search-input {
    width: 180px;
    color: inherit;

    /deep/ .ant-select-selection {
      background-color: inherit;
      border: 0;
      border-bottom: 1px solid white;
      &__placeholder, &__field__placeholder {
        color: inherit;
      }
    }
  }
</style>

<style scoped>
  .logout_title {
    color: inherit;
    text-decoration: none;
  }
</style>
